<template>
	<div>
		<el-dialog
			:visible.sync="visible"
			title="详情"
			:close-on-click-modal="false"
			class="m-view-dialog m-view-dialog_center"
			lock-scroll
			:width="formData.popupWidth"
			:append-to-body="true"
		>
			<div
				v-loading="loading || mainLoading"
				class="m-view-dynamic-detail"
			>
				<Parser
					v-if="!loading"
					:data="formData"
					:relation-data="relationData"
					:form-value="formValue"
					@to-detail="toDetail"
				/>
			</div>
			<template #footer>
				<span
					class="dialog-footer"
				>
					<template v-if="formData.hasPrintBtn && formData.printId">
						<el-button
							type="primary"
							@click="print"
						>
							{{formData.printButtonText || "打 印"}}
						</el-button>
					</template>
					<el-button @click="visible = false">取消</el-button>
				</span>
			</template>
		</el-dialog>
		<RelevanceDetail
			v-if="detailVisible"
			ref="RelevanceDetail"
			@close="detailVisible = false"
		/>
		<!-- <PrintBrowse :id="printId" :visible.sync.sync="printBrowseVisible" :formId="dataForm.id" /> -->
		<!-- <PrintDialog v-if="printDialogVisible" ref="printDialog" @change="printBrowseHandle">
        </PrintDialog> -->
	</div>
</template>

<script>
import {cloneDeep} from './../../utils/index.js';
import Parser from './detail/Parser';
import {magic} from '@lexmis/magic-ui/pc';
/* ⬇️ 未迁移功能 ⬇️*/
// import PrintDialog from "@/components/PrintDialog";
// import {getDataChange, getConfigData} from '@/api/onlineDev/visualDev';
// import {getDataInterfaceDataInfoByIds} from '@/api/systemData/dataInterface';
// import PrintBrowse from "@/components/PrintBrowse";
export default {
	name:'RelevanceDetail',
	components:{
		Parser,
    // PrintBrowse,
    // PrintDialog
	},
	data(){
		return {
			printId:'',
			printDialogVisible:false,
			visible:false,
			dataForm:{
				id:'',
				data:'',
			},
			modelId:'',
			formData:{},
			formValue:{},
			loading:true,
			mainLoading:false,
			detailVisible:false,
			relationData:{},
			useFormPermission:false,
			printBrowseVisible:false,
			formOperates:[],
		};
	},
	methods:{
		goBack(){
			this.$emit('close');
		},
		printBrowseHandle(id){
			this.printDialogVisible = false;
			this.printId = id;
			this.printBrowseVisible = true;
		},
		print(){
			if(this.isPreview){
				return this.$message({message:'功能预览不支持打印', type:'warning'});
			}
			this.printDialogVisible = true;
			this.$nextTick(() => {
				if(this.formData.printId.length === 1){
					this.printBrowseHandle(this.formData.printId[0]);
					return;
				}
				this.$refs.printDialog.init(this.formData.printId);
			});
		},
		init(formData, modelId, id, useFormPermission){
			this.formData = cloneDeep(formData);
			this.modelId = modelId;
			this.useFormPermission = useFormPermission;
			this.dataForm.id = id || '';
			this.dataForm.templateId = modelId || '';
			this.getFormOperates();
			this.loading = true;
			this.relationData = {};
			this.$nextTick(() => {
				if(this.dataForm.id){
					magic.core.service({
						url:'/api/form/instance/data-text',
						method:'get',
						params:{
							templateId:modelId,
							id:id,
						},
					}).then(({data}) => {
						this.dataForm = data;
						if(!this.dataForm.data) return;
						this.formValue = this.dataForm.data;
						this.fillFormData(this.formData, this.formValue);
						this.initRelationForm(this.formData.fields);
						this.visible = true;
					});
				}else{
					this.formValue = {};
					this.loading = false;
					this.visible = false;
					this.$emit('close');
				}
			});
		},
		initRelationForm(componentList){
			componentList.forEach((cur) => {
				const config = cur.config;
				if(config.identity === 'relationFormAttr' || config.identity === 'popupAttr'){
					const relationKey = cur.relationField.split('__Table__')[0];
					componentList.forEach((item) => {
						const noVisibility
							= Array.isArray(item.config.visibility)
							&& !item.config.visibility.includes('pc');
						if(relationKey === item.model && (noVisibility || !!item.hidden)){
							cur.hidden = true;
						}
					});
				}
				if(cur.config.children && cur.config.children.length){
					this.initRelationForm(cur.config.children);
				}
			});
		},
		unique(arr, attrName){
			const res = new Map();
      // 根据对象的某个属性值去重
			return arr.filter((o) => !res.has(o[attrName]) && res.set(o[attrName], 1));
		},
		handleAttrList(list){
			const realList = this.unique(list, 'relationField');
			for(let i = 0; i < realList.length; i++){
				const item = realList[i];
				let modelId = '';
				let id = '';
				let field = '';
				let identity = '';
				let activeItem = {};
				const prop = item.relationField.split('__Table__')[0];
				const loop = (list) => {
					for(let i = 0; i < list.length; i++){
						if(prop === list[i].model){
							identity = list[i].config.identity;
							modelId
								= list[i].config.identity === 'relationForm' ? list[i].modelId : list[i].interfaceId;
							id = list[i].config.defaultValue;
							field = list[i].config.tableName
								? list[i].model
								+ '__Table__'
								+ list[i].config.tableName
								+ (list[i].config.isSubTable ? '0' : '1')
								: list[i].model;
							activeItem = list[i];
							break;
						}
						if(
							list[i].config
							&& list[i].config.identity !== 'table'
							&& list[i].config.children
							&& Array.isArray(list[i].config.children)
						){
							loop(list[i].config.children);
						}
					}
				};
				loop(this.formData.fields);
				if(!id){
					this.$set(this.relationData, field, '');
					continue;
				}
				if(identity === 'relationForm'){
          // getDataChange(modelId, id)
          // 	.then((res) => {
          // 		if(!res.data || !res.data.data){
          // 			this.$set(this.relationData, field, '');
          // 			return;
          // 		}
          // 		const data = JSON.parse(res.data.data);
          // 		this.$set(this.relationData, field, data);
          // 	})
          // 	.catch(() => {
          // 		this.$set(this.relationData, field, '');
          // 	});
				}
				if(identity === 'popupSelect'){
          // const paramList = this.getParamList(activeItem);
          // const query = {
          // 	ids:[id],
          // 	interfaceId:modelId,
          // 	propsValue:activeItem.propsValue,
          // 	relationField:activeItem.relationField,
          // 	paramList,
          // };
          // getDataInterfaceDataInfoByIds(modelId, query)
          // 	.then((res) => {
          // 		if(!res.data) return this.$set(this.relationData, field, '');
          // 		this.$set(
          // 			this.relationData,
          // 			field,
          // 			res.data && res.data.length ? res.data[0] : {},
          // 		);
          // 	})
          // 	.catch(() => {
          // 		this.$set(this.relationData, field, '');
          // 	});
				}
			}
		},
		getParamList(activeItem){
			const templateJson = activeItem.templateJson;
			if(!this.formValue) return templateJson;
			for(let i = 0; i < templateJson.length; i++){
				if(templateJson[i].relationField){
					if(templateJson[i].relationField.includes('-')){
						const tableVModel = templateJson[i].relationField.split('-')[0];
						const childVModel = templateJson[i].relationField.split('-')[1];
						templateJson[i].defaultValue
							= (this.formValue[tableVModel]
								&& this.formValue[tableVModel][this.rowIndex]
								&& this.formValue[tableVModel][this.rowIndex][childVModel])
								|| '';
					}else{
						templateJson[i].defaultValue
							= this.formValue[templateJson[i].relationField] || '';
					}
				}
			}
			return templateJson;
		},
		toDetail(item){
			if(!item.config.defaultValue) return;
			this.mainLoading = true;
			magic.core.service({
				url:`/api/form/instance/config`,
				method:'get',
				params:{templateId:item.config.dataTypeId},
			}).then(({data}) => {
				this.mainLoading = false;
				if(!data?.formData) return;
				const formData = data.formData;
				formData.popupType = this.formData.popupType;
				this.detailVisible = true;
				this.$nextTick(() => {
					this.$refs.RelevanceDetail.init(formData, item.config.dataTypeId, item.config.defaultValue);
				});
			}).catch(() => {
				this.mainLoading = false;
			});

      // getConfigData(item.config.dataTypeId)
      // 	.then((res) => {
      // 		this.mainLoading = false;
      // 		if(!res.data) return;
      // 		if(!res.data.formData) return;
      // 		const formData = JSON.parse(res.data.formData);
      // 		formData.popupType = this.formData.popupType;
      // 		this.detailVisible = true;
      // 		this.$nextTick(() => {
      // 			this.$refs.Detail.init(formData, item.config.dataTypeId, item.config.defaultValue);
      // 		});
      // 	})
      // 	.catch(() => {
      // 		this.mainLoading = false;
      // 	});
		},
		getFormOperates(){
			if(!this.useFormPermission) return;
			const permissionList = this.$store.getters.permissionList;
			const modelId = this.$route.meta.modelId;
			const list = permissionList.filter((o) => o.modelId === modelId);
			this.formOperates = list[0] && list[0].form ? list[0].form : [];
		},
		fillFormData(form, data){
			const relationFormAttrList = [];
			const loop = (list, parent) => {
				for(let i = 0; i < list.length; i++){
					const item = list[i];
					if(item.model){
						if(
							item.config.identity === 'relationForm'
							|| item.config.identity === 'popupSelect'
						){
							item.config.defaultValue = data[item.model + '_id'];
							this.$set(item, 'name', data[item.model] || '');
						}else{
							const val = Object.prototype.hasOwnProperty.call(data, item.model)
								? data[item.model]
								: item.config.defaultValue;
							item.config.defaultValue = val;
						}
						if(this.useFormPermission){
							const id = item.config.isSubTable
								? parent.model + '-' + item.model
								: item.model;
							let noShow = true;
							if(this.formOperates && this.formOperates.length){
								noShow = !this.formOperates.some((o) => o.enCode === id);
							}
							noShow = item.hidden ? item.hidden : noShow;
							this.$set(item.config, 'noShow', noShow);
						}
					}
					if(['relationFormAttr', 'popupAttr'].includes(item.config.identity)){
						relationFormAttrList.push(item);
					}
					if(
						item.config
						&& item.config.children
						&& Array.isArray(item.config.children)
					){
						loop(item.config.children, item);
					}
				}
			};
			loop(form.fields);
			this.handleAttrList(relationFormAttrList);
			this.loading = false;
		},
	},
};
</script>